package com.tanhua.sso.service;

import com.google.common.annotations.VisibleForTesting;
import com.tanhua.sso.config.IhuyiSmsConfig;
import com.tanhua.sso.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;


/**
 * @Auther: you
 * @Date: 2021/05/25/10:52
 * @Description:
 */
@Service
@Slf4j
public class SmsService {
    @Autowired
    private IhuyiSmsConfig ihuyiSmsConfig;

    @Autowired
    private RedisTemplate redisTemplate;



    /**
     * @Description: 对指定手机号mobile,发送验证码
     * @Author: you
     * @Date:   2021/5/25 0025 16:09
     * @Param:  [mobile]
     * @Return: java.lang.String
     */
    public String sendSms(String mobile) {
        //互亿无线apiId
        String apiId = ihuyiSmsConfig.getApiId();
        //互亿无线apiKey
        String apiKey = ihuyiSmsConfig.getApiKey();
        //互亿无线url
        String url = ihuyiSmsConfig.getUrl();

        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(url);

        client.getParams().setContentCharset("GBK");
        method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=GBK");

//        int mobile_code = (int) ((Math.random() * 9 + 1) * 100000);
        int mobile_code =111122;

        String content = new String("您的验证码是：" + mobile_code + "。请不要把验证码泄露给其他人。");

        NameValuePair[] data = {//提交短信
                new NameValuePair("account",apiId), //查看用户名 登录用户中心->验证码通知短信>产品总览->API接口信息->APIID
                new NameValuePair("password", apiKey), //查看密码 登录用户中心->验证码通知短信>产品总览->API接口信息->APIKEY
                //new NameValuePair("password", util.StringUtil.MD5Encode("密码")),
                new NameValuePair("mobile", mobile),
                new NameValuePair("content", content),
        };
        method.setRequestBody(data);

        try {
            client.executeMethod(method);

            String SubmitResult = method.getResponseBodyAsString();
            Document doc = DocumentHelper.parseText(SubmitResult);
            Element root = doc.getRootElement();

            String code = root.elementText("code");
            String msg = root.elementText("msg");
            String smsid = root.elementText("smsid");

            System.out.println("---------------------------------SendSMsService--------------------------");
            System.out.println(code);
            System.out.println(msg);
            System.out.println(smsid);
            System.out.println("验证码为："+mobile_code);
            System.out.println("---------------------------------SendSMsService--------------------------");

            //发送状态码为2，发送成功，返回发送的验证码
            if ("2".equals(code)) {
                System.out.println("短信提交成功");
                return String.valueOf(mobile_code);
            }

            //状态码不为2，发送失败，返回失败信息和发送状态码
            log.error("发送短信验证码失败~ mobile= "+mobile+",code="+code);

        } catch (Exception e) {
            //抛异常，发送失败，并发送异常信息
            log.error("发送短信验证码失败~ mobile= "+mobile,e);
        }

        return null;

    }

    /**
     * @Description: 验证手机号，是否 5 分钟内发送过验证码，没有，则重新发送，并将验证码存储在redis
     *               中，设定 5 分钟过期时效
     * @Author: you
     * @Date:   2021/5/25 0025 16:09
     * @Param:  [phone]
     * @Return: com.tanhua.sso.com.tanhua.common.vo.ErrorResult
     */
    public ErrorResult sendCheckCode(String phone) {
        String redisKey="CHECK_CODE_"+phone;

        //发送的验证码还未过期
        if (redisTemplate.hasKey(redisKey)){
            String msg="上次生成的验证码还未失效";
            return ErrorResult.builder().errCode("000001").errMessage(msg).build();
        }

//        String code = sendSms(phone);
        String code = "123456";


        //验证码发送失败
        if (StringUtils.isEmpty(code)){
            String msg="发送验证码失败";
            return ErrorResult.builder().errCode("000002").errMessage(msg).build();
        }

        //短信发送成功，将验证码保存在redis缓存中，有效期5分钟
        redisTemplate.opsForValue().set(redisKey,code, Duration.ofMinutes(5));


        Object o = redisTemplate.opsForValue().get(redisKey);

        System.out.println(redisKey);

        System.out.println(o);


        return null;

    }
}
